#include "centrifier.h"

#include <QEvent>

Centrifier::Centrifier( QScrollArea* area, QWidget* widget, QWidget* parent):
        QWidget(parent)
{
    this->area = area;
    this->widget = widget;
    this->widget->setParent( this );
    this->area->setWidget( this );

    this->area->viewport()->installEventFilter( this );
    this->widget->installEventFilter( this );

    reLayout();
}

bool Centrifier::eventFilter( QObject * o, QEvent * e )
{
   if ((o == area->viewport() && e->type() == QEvent::Resize))
   {
       reLayout();
       return false;
   }

   return QWidget::eventFilter( o, e );
}

void Centrifier::reLayout()
{
   const QSize widgetSize = widget->size();
   const QSize viewPortSize = area->viewport()->size();
   const QSize diffSize = viewPortSize - widgetSize;

   resize( QSize(
            qMax( widgetSize.width(), viewPortSize.width() ),
            qMax( widgetSize.height(), viewPortSize.height() ) ) );

   widget->move(
      diffSize.width() <= 0 ? 0 : diffSize.width() / 2,
      diffSize.height() <= 0 ? 0 : diffSize.height() / 2 );
}
